<?php
namespace Home\Controller;
use Think\Controller;
class ChatController extends CommonController {
	//获取好友列表及基本信息
	public function getFriendList(){
		$id=$_SESSION['home']['uid'];
		$ring=M('Ring');

		//获取所有本账号好友意向
		$user_id_b=$ring
		->field('user_id_b')
		->where('user_id_a='.$id)
		->buildSql();

		//获取所有本账号好友意向的好友意向，根据本账号ID筛选出好友
		$friend_id=$ring
		->field('user_id_a as friend_id')
		->where('user_id_a in '.$user_id_b.' and user_id_b='.$id)
		->buildSql();

		//获取所有好友信息
		$user=M('User');
		$friendList=$user->alias('user')
		->field('user.user_id,username,online,nickname,signature,photo')
		->join('__USER_INFO__ on user.user_id = __USER_INFO__.user_id')
		->where('user.user_id in '.$friend_id)
		->select();

		// var_dump($friendList);
		echo $this->ajaxReturn($friendList);
	}

	//发送聊天消息
	public function sendChatMessages(){
		$id=$_SESSION['home']['uid'];
		$friend_id=I('post.id',0,'int');

		$data=array(
			'user_id_a' =>$_SESSION['home']['uid'],
			'user_id_b' =>I('post.id',0,'int'),
			'content'   =>I('post.content','','string'),
			'time'      =>$_SERVER['REQUEST_TIME']
		);

		$chat=M('Chat');
		if($chat->create($data)){
			$id=$chat->add($data);
			$result=array(
				'status' =>1,
				'id'     =>$id
			);
		}else{
			$result=array('status'=>0);
		}
		$this->ajaxReturn($result);
	}

	//获取聊天记录
	public function getChatHistory(){
		$id=$_SESSION['home']['uid'];
		$friend_id=I('get.id',0,'int');
		$chatLastId=I('get.lastid',0,'int');
		if($friend_id){
			$chat=M('Chat');
			$userA=$chat->where('user_id_a='.$id.' and user_id_b='.$friend_id.' and chat_id>'.$chatLastId)->select();
			if($userA===null){
				$userA=array();
			}
			$userB=$chat->where('user_id_a='.$friend_id.' and user_id_b='.$id.' and chat_id>'.$chatLastId)->select();
			if($userB===null){
				$userB=array();
			}
			$res=array_merge($userA,$userB);
			//按chat_id升序
			$res=arraySortByKey($res,'chat_id',true);
			//截取20条消息
			$res=array_slice($res,-20,20);
			$result=array(
				'status'  =>1,
				'content' =>$res
			);
		}else{
			$result=array('status'=>0);
		}
		// var_dump($result);
		$this->ajaxReturn($result);
	}
}
